home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / ProgramD2.iso / Borland / Borland C++ V5.02 / STDLIB.PAK / EXCEPTN.CPP < prev    next >
C/C++ Source or Header  |  1997-05-06  |  2KB  |  63 lines

  1. /**************************************************************************
  2.  *
  3.  * exceptn.cpp - Illustrate the use of Standard exceptions.
  4.  *    Section 13
  5.  *
  6.  * $Id: exceptn.cpp,v 1.1 1995/10/09 02:47:12 smithey Exp $
  7.  *
  8.  * $$RW_INSERT_HEADER "slyrs.cpp"
  9.  *
  10.  **************************************************************************/
  11.  
  12. #include <stdexcept>
  13. #include <string>
  14.  
  15. using namespace std;
  16.  
  17. #ifdef RWSTD_NO_EXCEPTIONS
  18. int main ()
  19. {
  20.     cout << "Your compiler doesn't support exceptions!" << endl;
  21.     return 0;
  22. }
  23. #else
  24.  
  25. // A simple class to demonstrate throwing an exception
  26. static void f() { throw runtime_error("a runtime error"); }
  27.  
  28. int main ()
  29. {
  30.   string s;
  31.   
  32.   // First we'll try to incite and catch an exception from
  33.   // the standard library string class.
  34.   // We'll try to replace at a position that is non-existant.
  35.   //
  36.   // By wrapping the body of main in a try-catch block we can be
  37.   // assured that we'll catch all exceptions in the exception hierarchy.
  38.   // You can simply catch exception as is done below, or you can catch
  39.   // each of the exceptions in which you have an interest.
  40.   try
  41.   {
  42.     s.replace(100,1,1,'c');
  43.   }
  44.   catch (const exception& e)
  45.   {
  46.     cout << "Got an exception: " << e.what() << endl;
  47.   }
  48.  
  49.   // Now we'll throw our own exception using the function 
  50.   // defined above.
  51.   try
  52.   {
  53.     f();
  54.   }
  55.   catch (const exception& e)
  56.   {
  57.     cout << "Got an exception: " << e.what() << endl;
  58.   }
  59.  
  60.  return 0;
  61. }
  62. #endif /*RWSTD_NO_EXCEPTIONS*/
  63.